package com.tanhua.server.service;

import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.constant.Constants;
import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.dubbo.api.db.UserApi;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.FriendApi;
import com.tanhua.model.db.User;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.ContactVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 消息管理-业务处理层
 */
@Service
@Slf4j
public class MessagesService {

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private FriendApi friendApi;

    /**
     * 环信ID查询用户信息
     */
    public UserInfoVo findUserByHuanxinUser(String huanxinId) {
        //1 根据huanxinId查询user对象
        User user = userApi.findByHuanxinUser(huanxinId);
        Long userId = user.getId();
        //2 根据userId查询userInfo
        UserInfo userInfo = userInfoApi.getUserInfo(userId);
        //3 基于userInfo构造userInfoVo
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,userInfoVo);
        userInfoVo.setId(userId);
        return userInfoVo;
    }

    /**
     * 联系人添加
     */
    public void makeFriends(Long friendUserId) {
        Long userId = UserHolder.getUserId();
        //1 调用环信云添加好友关系
        if(!huanXinTemplate.addContact(Constants.HX_USER_PREFIX+userId.toString(),Constants.HX_USER_PREFIX+friendUserId.toString())){
            throw new TanHuaException(ErrorResult.error());
        }
        //2 调用服务将好友关系写入好友表
        friendApi.makeFriends(userId,friendUserId);
        log.debug("***********添加联系人成功了******当前用户{}*****好友用户{}********",userId,friendUserId);
    }

    /**
     * 联系人列表分页查询
     */
    public PageResult<ContactVo> findPageContacts(Long page, Long pageSize, String keyword) {
        //1 根据当前用户id与分页参数调用服务分页查询好友列表数据
        PageResult<Friend> friendPageResult = friendApi.findPageContacts(page,pageSize,UserHolder.getUserId());
        if (friendPageResult == null || CollectionUtils.isEmpty(friendPageResult.getItems())) {
            return new PageResult<>(0l, 10l, 0l, 1l, null);
        }
        //2 获取所有好友ids
        List<Friend> friendList = friendPageResult.getItems();
        List<Long> listFriendUserIds = friendList.stream().map(Friend::getFriendId).collect(Collectors.toList());
        //3.根据好友ids以及keyword关键字获取所有好友详情数据
        UserInfo uc = new UserInfo();
        uc.setNickname(keyword);
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(listFriendUserIds, uc);
        //4.基于好友详情数据 构造 Vo返回
        List<ContactVo> contactVoList = new ArrayList<>();
        for (Friend friend : friendList) {
            UserInfo userInfo = userInfoMap.get(friend.getFriendId());//获取好友用户详情
            if(null != userInfo) {
                ContactVo contactVo = ContactVo.init(userInfo);
                contactVoList.add(contactVo);
            }
        }


        /*Set<Long> longs = userInfoMap.keySet();
        for (Long userId : longs) {
            UserInfo userInfo = userInfoMap.get(userId);
            ContactVo contactVo = ContactVo.init(userInfo);
            contactVoList.add(contactVo);
        }*/
        return new PageResult<>(page,(long)contactVoList.size(),friendPageResult.getCounts(),contactVoList);
    }
}
